package com.harvest.scientific.ladder.net

import okhttp3.ConnectionPool
import okhttp3.ConnectionSpec
import okhttp3.OkHttpClient
import retrofit2.Retrofit
import retrofit2.converter.gson.GsonConverterFactory
import java.util.concurrent.TimeUnit

abstract class AbaRfit {

    private val mRetrofitMap: MutableMap<String, Retrofit?> = mutableMapOf()
    private val mOkClientMap: MutableMap<String, OkHttpClient?> = mutableMapOf()

    private val HTTP_CONNECT_TIMEOUT = 3000L
    private val HTTP_READ_TIMEOUT = 1500L
    private val HTTP_WRITE_TIMEOUT = 1500L
    private val HTTP_THREAD_POOL_SIZE = 16

    open fun <Service> getService(url: String, serviceClass: Class<Service>?): Service {
        if (null == serviceClass) throw RuntimeException("api service is null !")
        return getRetrofit(url).create(serviceClass)
    }

    private fun getRetrofit(url: String): Retrofit {
       if (null == mRetrofitMap[url]) {
           val retrofit = Retrofit.Builder()
               .client(getClient(url))
               .baseUrl(url)
               .addConverterFactory(GsonConverterFactory.create())
               .build()
           mRetrofitMap[url] = retrofit
       }
        return mRetrofitMap[url]!!
    }

    private fun getClient(url: String): OkHttpClient {
        if (null == mOkClientMap[url]) {
            val okHttpClient = OkHttpClient.Builder()
                .connectionSpecs(
                    listOf(
                        ConnectionSpec.MODERN_TLS,
                        ConnectionSpec.COMPATIBLE_TLS,
                        ConnectionSpec.CLEARTEXT
                    )
                )
                .sslSocketFactory(
                    Ssclient.sslSocketFactory,
                    Ssclient.trustManager
                )
                .hostnameVerifier(
                    Ssclient.hostnameVerifier
                )
                .connectTimeout(
                    HTTP_CONNECT_TIMEOUT, TimeUnit.MILLISECONDS
                )
                .readTimeout(
                    HTTP_READ_TIMEOUT, TimeUnit.MILLISECONDS
                )
                .writeTimeout(
                    HTTP_WRITE_TIMEOUT, TimeUnit.MILLISECONDS
                )
                .connectionPool(
                    ConnectionPool(HTTP_THREAD_POOL_SIZE,5, TimeUnit.MINUTES)
                )
                .addInterceptor(
                    BaCeptor()
                )
                .addInterceptor(
                    LogCeptor()
                )
                .build()
            mOkClientMap[url] = okHttpClient
        }
        return mOkClientMap[url]!!
    }

}